package com.portal.service.impl;

import com.portal.constant.RedisConst;
import com.portal.model.entity.Book;
import com.portal.model.vo.CartItemVo;
import com.portal.model.vo.CartVo;
import com.portal.service.BookService;
import com.portal.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BookService bookService;

    @Override
    public CartVo getCart(Long userId) {
        // 1、从Redis中获取购物车
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        CartVo cartVo = (CartVo) redisTemplate.opsForValue().get(key);

        // 2、如果第一次添加，需要创建一个购物车对象CartVo
        if (cartVo == null) {
            cartVo = new CartVo();
            cartVo.setUserId(userId);

            // 3、将数据存入Redis
            redisTemplate.opsForValue().set(key, cartVo);
        }
        return cartVo;
    }

    @Override
    public CartVo addCartItem(Long userId, Long bookId) {
        CartVo cartVo = getCart(userId);
        // 查询图书
        Book book = bookService.findById(bookId);
        // 转换： Book  -->  CartItemVo
        CartItemVo cartItemVo = new CartItemVo(userId, bookId, book.getName(), book.getImgSrc(), book.getPrice(), 1);
        // 添加到购物车对象中
        cartVo.addItem(cartItemVo);
        // 存储到Redis中, 默认7天有效
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        redisTemplate.opsForValue().set(key, cartVo, 7, TimeUnit.DAYS);
        return cartVo;
    }

    @Override
    public void clearCart(Long userId) {
        CartVo cart = getCart(userId);
        cart.clearCart();
        redisTemplate.delete(RedisConst.USER_CART_PREFIX + ":" + userId);
    }
}












